package server.gameplay;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import network.protocol.Protocol;

import server.network.ServerInterface;

public class SendUnitQue {
	ArrayList<SendReq> list;
	ArrayList<SendReq> removeList;
	List<Unit> units;
	ServerInterface gamePlay;

	public SendUnitQue(List<Unit> units2, ServerInterface gamePlay) {
		list = new ArrayList<SendReq>();
		units = units2;
		removeList = new ArrayList<SendReq>();
		this.gamePlay = gamePlay;
	}

	public void add(Building b, Building targetBuilding, double quota) {
		synchronized (this) {
			int n = (int) ((double) (b.getResidents()) * quota);
			Iterator<SendReq> itr = list.iterator();
			while (itr.hasNext()) {
				if (itr.next().sameReq(b.getPath(targetBuilding.getPos()), n))
					return;
			}
			list.add(new SendReq(b.getPath(targetBuilding.getPos()), b
					.getOwner(), b, n, targetBuilding));
		}
	}

	public void performSendRequest() {
		for (int i = 0; i < list.size(); i++) {
			send(list.get(i).grantReq(), list.get(i));
			if (!list.get(i).moreReq()) {
				removeList.add(list.get(i));
			}
		}
		for (int i = 0; i < removeList.size(); i++) {
			list.remove(removeList.get(i));
		}
		removeList.clear();
	}

	private void send(int grantReq, SendReq sendReq) {
		synchronized (this) {
			for (int n = 0; n < grantReq; n++) {
				if (sendReq.getBuilding().getResidents() >= 1) {
					units.add(new Unit(sendReq.getTarget(), sendReq.getOwner(),
							sendReq.getPath().getPath(n), (float)sendReq.getPath()
									.getSpeed(n)));
					sendReq.getBuilding().sendAwayUnit();
				} else {
					// building is empty! send info to clients!
					gamePlay.broadcast(
							Integer.toString(sendReq.getBuilding().getIndex()),
							Protocol.BUILDING_IS_EMPTY);
					sendReq.clear();
					return;
				}
			}
		}
	}
}
